package com.aaa.dao.impl;

import com.aaa.dao.CommentDao;
import com.aaa.entity.Comment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Controller;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

@Controller
public class CommentDaoImpl implements CommentDao {
    @Autowired
    private JdbcTemplate jdbcTemplate;

    private RowMapper<Comment> rowMapper = new RowMapper<Comment>() {
        public Comment mapRow(ResultSet resultSet, int i) throws SQLException {
            Comment comment = new Comment();
            comment.setId(resultSet.getInt("id"));
            comment.setComme(resultSet.getString("comme"));
            return comment;
        }
    };

    public List<Comment> listPage(String keyword, Integer offset, Integer limit) {
        String sql = "select id,comme from comment where comme like ? order by id desc limit ?,?";
        List<Comment> count = this.jdbcTemplate.query(sql, rowMapper, "%" + keyword + "%", offset, limit);
        return count;
    }

    public Integer count(String keyword) {
        String sql = "select count(id) as c from comment where comme like ?";
        Integer result = this.jdbcTemplate.queryForObject(sql, new RowMapper<Integer>() {
            public Integer mapRow(ResultSet resultSet, int i) throws SQLException {
                return resultSet.getInt("c");
            }
        },"%" + keyword + "%");
        return result;
    }

    public Integer save(Comment comment) {
        String sql = "insert into comment(comme) values(?)";
        int count = jdbcTemplate.update(sql, comment.getComme());
        return count;
    }

    public Integer update(Comment comment) {
        String sql = "update comment set comme=? where id=?";
        int count = jdbcTemplate.update(sql, comment.getComme(), comment.getId());
        return count;
    }

    public Integer delete(Integer id) {
        String sql = "delete from comment where id=?";
        int count = jdbcTemplate.update(sql, id);
        return count;
    }
}
